package com.tian.service.impl;

import com.tian.enums.MessageFailedRetryTypeEnum;
import com.tian.mapper.RetryMessageMapper;
import com.tian.producer.DelayDeleteCacheProducer;
import com.tian.service.DelayDeleteCacheMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * {@code @description:} 延迟删除缓存补发消息服务实现类
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2025-03-03 9:26
 * {@code @version:} 1.0
 */
@Slf4j
@Service
public class DelayDeleteCacheMessageServiceImpl implements DelayDeleteCacheMessageService {
    @Resource
    private DelayDeleteCacheProducer delayDeleteCacheProducer;
    @Resource
    private RetryMessageMapper retryMessageMapper;

    @Override
    public void process() {
        int count = retryMessageMapper.countRetryMessage(MessageFailedRetryTypeEnum.DELAY_DELETE_CACHE.getCode(), 0);
        if (count == 0) {
            log.info("【延迟删除缓存】没有需要处理的消息");
        }
        log.info("【延迟删除缓存】有{}条需要处理的消息", count);
        int batchSize = 100;
        int total = count / batchSize;
        if (count % batchSize!= 0) {
            total++;
        }
        for (int i = 0; i < total; i++){
            retryMessageMapper.selectRetryMessagePage(MessageFailedRetryTypeEnum.DELAY_DELETE_CACHE.getCode(),
                    0, i * batchSize, batchSize).forEach(message -> {
                delayDeleteCacheProducer.delayDeleteCache(message);
            });
        }
    }
}
